﻿<%@ WebHandler Language="C#" Class="RbSendToDataWenterHandler" %>

/*Description: 热表推送数据中心管理
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20240903
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Collections;
using NPOI.SS.UserModel;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using BusinessRule.Common;

public class RbSendToDataWenterHandler : IHttpHandler
{
    string fileBasePath = "/InSiteWebApplication/Temp2/RBSendToDC/";//上传文件地址
    string rbFactoryID = System.Configuration.ConfigurationManager.AppSettings["RBFactoryID"].ToString(); //热表ID
    string toAppId = System.Configuration.ConfigurationManager.AppSettings["ToAppID_RB"].ToString();////数据中心推送目的ID（热表）
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string action = context.Request["action"].ToString();
            switch (action)
            {
                case "GetSendRecord": //获取推送记录（弃用）
                    GetSendRecord(context);
                    break;
                case "UploadFilesToDC": //上传文件
                    UploadFilesToDC(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未知功能" }));
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 上传文件，并写入推送数据中心记录表中，由服务推送完成
    /// </summary>
    /// <param name="context"></param>
    private void UploadFilesToDC(HttpContext context)
    {
        string fpath = string.Empty;
        try
        {
            HttpFileCollection files = context.Request.Files;
            if (files.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未上传文件！", Result = false }));
                return;
            }
            HttpPostedFile file = files.Count > 1 ? files[files.Count - 1] : files[0];//只取一个文件
            string fileNameOutExtension = Path.GetFileNameWithoutExtension(file.FileName);//不带扩展名的文件名
            if (string.IsNullOrWhiteSpace(fileNameOutExtension))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "文件名为空！", Result = false }));
                return;
            }
            if (fileNameOutExtension.Length < 4 || (fileNameOutExtension[fileNameOutExtension.Length - 2] != '部' && fileNameOutExtension[fileNameOutExtension.Length - 3] != '内'))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "文件名尾部必须包含（内部）且文件名不能只为（内部）！", Result = false }));
                return;
            }
            fileBasePath = string.Format("{0}{1}/", fileBasePath, DateTime.Now.Year.ToString());
            fpath = context.Server.MapPath(fileBasePath);//获取物理地址
            if (!Directory.Exists(fpath))//如果文件路径不存在，则创建
            {
                Directory.CreateDirectory(fpath);
            }
            fpath = fpath + file.FileName;//保存的地址
            if (File.Exists(fpath) || DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM objectdocinfo o WHERE o.filename = '{0}' AND o.parentid = '{1}'", file.FileName, rbFactoryID)) != null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "已存在相同名称的文件！", Result = false }));
                return;
            }
            file.SaveAs(fpath);//保存文件
            /*保存附件路径到附件表*/
            ArrayList sqlList = new ArrayList();
            string objectdocinfoID = Guid.NewGuid().ToString();
            string sql = "INSERT INTO OBJECTDOCINFO ob (ob.objectdocinfoid,ob.parentid,ob.filepath,ob.filename) VALUES('{0}','{1}','{2}','{3}')";
            sqlList.Add(string.Format(sql, objectdocinfoID, rbFactoryID, string.Format("{0}{1}", fileBasePath, file.FileName), file.FileName));
            /*将附件表插入到推送记录表*/
            string recordID = Guid.NewGuid().ToString();
            sql = "INSERT INTO sync_tablechangerecord (id,tablename,uniquecolname,uniquecolvalue,operatetype) VALUES('{0}','{1}','{2}','{3}',1)";
            sqlList.Add(string.Format(sql, recordID, "OBJECTDOCINFO", "OBJECTDOCINFOID", objectdocinfoID));
            sql = "INSERT INTO sync_sendtoappid (parentid,toappid)values('{0}','{1}')";
            sqlList.Add(string.Format(sql, recordID, toAppId));
            /*最终执行sql*/
            DatabaseHelper.ExecuteSqlTran(sqlList);
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "保存成功！", Result = true }));
        }
        catch (Exception ex)
        {
            DeleteFile(fpath);//报错，则删除上传的文件
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = ex.Message, Result = false }));
        }
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="fpath">文件地址</param>
    private void DeleteFile(string fpath)
    {
        if (File.Exists(fpath))
        {
            new FileInfo(fpath).Attributes = FileAttributes.Normal;
            File.Delete(fpath);
        }
    }

    /// <summary>
    /// 获取推送记录（弃用，并且只查询一部分数据）
    /// </summary>
    /// <param name="context"></param>
    public void GetSendRecord(HttpContext context)
    {
        string rbContainerName = context.Request["ContainerName"].ToString();
        string sql = string.Format(@" SELECT cci.containerid,csc.containersubcontainerid,w.workflowid,wb.workflowbaseid,
                                p.productid,pb.productbaseid,ws.workflowstepid,sb.specbaseid,sc.specid
                                FROM containersubcontainer csc 
                                INNER JOIN containercurrentinfo cci ON cci.containerid = csc.subcontainerid AND cci.isinstore != 1
                                LEFT JOIN container c ON c.containerid = cci.containerid
                                LEFT JOIN workflow w ON w.workflowid = DECODE(cci.isinstore,-1,c.mfgworkflowid,cci.workflowid)
                                LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                                LEFT JOIN product p ON p.productid = cci.productid
                                LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
                                LEFT JOIN workflowstep ws ON ws.workflowid = w.workflowid
                                LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                                LEFT JOIN spec sc ON sc.specid = NVL(sb.revofrcdid,ws.specid)
                                WHERE cci.containername = '{0}'
                                UNION ALL 
                                SELECT cci.containerid,'' containersubcontainerid,w.workflowid,wb.workflowbaseid,
                                p.productid,pb.productbaseid,ws.workflowstepid,sb.specbaseid,sc.specid
                                FROM containercurrentinfo cci
                                INNER JOIN userattribute u ON u.parentid = cci.containerid AND u.userattributename = '委托批次'
                                LEFT JOIN container c ON c.containerid = cci.containerid
                                LEFT JOIN workflow w ON w.workflowid = DECODE(cci.isinstore,-1,c.mfgworkflowid,cci.workflowid)
                                LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                                LEFT JOIN product p ON p.productid = cci.productid
                                LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
                                LEFT JOIN workflowstep ws ON ws.workflowid = w.workflowid
                                LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                                LEFT JOIN spec sc ON sc.specid = NVL(sb.revofrcdid,ws.specid)
                                WHERE cci.containername = '{0}' AND cci.isinstore != 1
                                ", rbContainerName);
        DataTable dtSubContainer = DatabaseHelper.Query_ReturnDatTable(sql);
        DataTable dt = new DataTable();
        DataView dvSubContainer = dtSubContainer.AsDataView();
        dt.Merge(GetSyncTableChangeRecord(dvSubContainer.ToTable(true, "containerid"), "container", "containerid"));
        dt.Merge(GetSyncTableChangeRecord(dvSubContainer.ToTable(true, "containersubcontainerid"), "containersubcontainer", "containersubcontainerid"));
        dt.Merge(GetSyncTableChangeRecord(dvSubContainer.ToTable(true, "workflowid"), "workflow", "workflowid"));
        dt.Merge(GetSyncTableChangeRecord(dvSubContainer.ToTable(true, "workflowbaseid"), "workflowbase", "workflowbaseid"));
        dt.Merge(GetSyncTableChangeRecord(dvSubContainer.ToTable(true, "productid"), "product", "productid"));
        dt.Merge(GetSyncTableChangeRecord(dvSubContainer.ToTable(true, "productbaseid"), "productbase", "productbaseid"));
        dt.Merge(GetSyncTableChangeRecord(dvSubContainer.ToTable(true, "workflowstepid"), "workflowstep", "workflowstepid"));
        dt.Merge(GetSyncTableChangeRecord(dvSubContainer.ToTable(true, "specbaseid"), "specbase", "specbaseid"));
        dt.Merge(GetSyncTableChangeRecord(dvSubContainer.ToTable(true, "specid"), "spec", "specid"));
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        result.DBTable = dt;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }


    private DataTable GetSyncTableChangeRecord(DataTable dtData, string tableName, string uniqueColName)
    {
        string Ids = string.Empty;
        foreach (DataRow item in dtData.Rows)
        {
            Ids += string.Format("'{0}',", item[uniqueColName].ToString());
        }
        Ids = Ids.TrimEnd(',');
        string sql = string.Format(@"SELECT st.tablename,st.id,st.operatetype,st.ismeshandle,st.uniquecolname,st.uniquecolvalue,
                        DECODE(st.operatetype,1,'新增',2,'更新',3,'删除','未知') typename,
                        DECODE(st.ismeshandle,1,'已推送','未推送') handleName
                        FROM sync_tablechangerecord st
                        LEFT JOIN sync_sendtoappid sto ON sto.parentid = st.id
                        WHERE sto.toappid = '{0}' AND st.tablename = '{1}' AND st.uniquecolname = '{2}' AND st.uniquecolvalue IN ({3})", toAppId, tableName.ToUpper(), uniqueColName.ToUpper(), Ids);
        return DatabaseHelper.Query_ReturnDatTable(sql);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}